package com.yun.zf.system.exception;

import com.yun.zf.common.utils.StringUtils;
import com.yun.zf.common.vo.Response;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {



    /**
     * 基础异常
     */
    @ExceptionHandler(BaseException.class)
    public Response baseException(BaseException e)
    {
        return Response.error(e.getMessage());
    }


    //捕获全局异常,处理所有不可知的异常
    @ExceptionHandler(value = Exception.class)
    Object handleException(Exception e, HttpServletRequest request) {
        log.error("url {}, msg {}", request.getRequestURL(), e.getMessage());
        return Response.error( "系统异常，请稍后在试"+request.getRequestURI());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(CustomException.class)
    public Response businessException(CustomException e)
    {
        if (StringUtils.isNull(e.getCode()))
        {
            return Response.error(e.getMessage());
        }
        return Response.error(e.getCode(), e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public Response validatedBindException(BindException e)
    {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return Response.error(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e)
    {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return Response.error(message);
    }

}
